import React, { Component, PropTypes, ReactDOM } from 'react';
import { connect } from 'dva';
import { message, Modal, Pagination, Popconfirm, Button, Spin, Alert } from 'antd';
import styles from './Users.css';
import moment from 'moment';
import Factory from '../factory';
import * as cm from '../../constants';
import * as datetime from '../../utils/datetime'
import dataEditCreate from '../addons/DataEdit'
import * as menuService from '../../services/menus';
import httpntlm from 'httpntlm';
const daoName = "SSRS_Report";
const EditFrom = dataEditCreate(daoName);
class SSRS_Report extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isFirstLoad: true,
      isParamsChange: true,
    };
  }
  componentWillMount() {
    const permID = this.props.permID
    this.props.dispatch({
      type: `${daoName}/fetchControls`,
      payload: { permID }
    });
  }
  componentDidMount() {
    this.renderReport()
  }
  componentDidUpdate() {
    if (this.state.isParamsChange) {
      this.renderReport()
    }
  }
  createHandler() {
    const form = this.refs.reportForm.getForm()
    const { controls, permID, odsDate, cmDate, menus, FTPDate, userID } = this.props
    let conts = controls[permID]
    let sjy = ""
    menus.map((c, i) => {
      if (permID === c.ID) {
        sjy = c.SJY
      }
    })
    form.validateFields((err, values) => {
      if (!err) {
        conts.map((c, i) => {
          if (c.dataType === "date" || c.dataType === "datetime") {
            values[c.name] = !values[c.name] ? "" : datetime.format(values[c.name], "yyyyMMdd")
          } else if (c.dataType === "month") {
            values[c.name] = !values[c.name] ? "" : datetime.format(values[c.name], "yyyyMM")
          } else {
            values[c.name] = values[c.name] === undefined ? "" : values[c.name]
          }
          if (c.multiple || c.type === 'checkbox-group') {
            values[c.name] = values[c.name].join(',');
          }
        })
        let date = "";
        let sdate = "";
        let edate = "";
        if (values.DATEDAY != undefined) {
          date = values.DATEDAY
        }
        if (values.EDATEDAY != undefined) {
          date = values.EDATEDAY
          edate = values.EDATEDAY
        }
        if (values.SDATEDAY != undefined) {
          sdate = values.SDATEDAY
        }
        if (permID !== 1053 && permID !== 7081 && permID !== 7082) {
          if (sjy === "EDW") {
            let scd = datetime.format(cmDate, "yyyyMMdd")
            if (date > scd) {
              message.error('超出系统数据日期，数仓数据日期为【' + datetime.format(cmDate, "yyyy-MM-dd") + '】');
              return;
            }
          } else if (sjy === "ODS") {
            let odsd = datetime.format(odsDate, "yyyyMMdd")
            if (date > odsd) {
              message.error('超出系统数据日期，ODS数据日期为【' + datetime.format(odsDate, "yyyy-MM-dd") + '】');
              return;
            }
          } else {
            let ftpd = datetime.format(FTPDate, "yyyyMMdd")
            if (date > ftpd) {
              message.error('超出系统数据日期，FTP利润数据日期为【' + datetime.format(FTPDate, "yyyy-MM-dd") + '】');
              return;
            }
          }
        }
        if (userID !== 951 && userID !== 299) { //高园、无锡分行顾诚杰除外
          if (permID === 6030 || permID === 7031 || permID === 7032 || permID === 7033 ||
            permID === 7034 || permID === 7035 || permID === 7093 || permID === 7094 || permID === 6062) {
            if (sdate.slice(0, 6) === "202204" || edate.slice(0, 6) === '202204') {
              message.error('不支持查询，查询失败！');
              return;
            }
          }
        }
        this.state.isParamsChange = true
        this.props.dispatch({
          type: `${daoName}/saveParamValues`,
          payload: { permID, values }
        });
      }
    });
  };
  renderReport() {
    if (!this.refs["ssrs_report"]) {
      return
    }
    const { permID, userID, orgID, pOrgID, paramValues, url, popedomTypes, offsetHeight, odsDate, sjy, cmDate, ftpDate } = this.props
    const pvals = paramValues[permID]

    const params = Object.keys(pvals).map(key => {
      return {
        Key: key,
        Value: pvals[key],
      }
    })
    this.state.isParamsChange = false
    const pTypes = popedomTypes[permID]
    let div = this.refs["ssrs_report"]
    div.innerHTML = ""
    let iframe = document.createElement("iframe")
    iframe.height = offsetHeight - 140
    iframe.width = "100%"
    iframe.style.frameborder = 0
    iframe.style.border = 0
    let form = document.createElement("form")
    form.action = url
    form.method = "post"
    form.height = offsetHeight - 130
    form.style.height = offsetHeight - 130
    let input1 = document.createElement("input");
    input1.type = "hidden";
    input1.name = "userID";
    input1.value = userID;
    let input2 = document.createElement("input");
    input2.type = "hidden";
    input2.name = "reportID";
    input2.value = permID
    let input3 = document.createElement("input");
    input3.type = "hidden";
    input3.name = "params";
    input3.value = JSON.stringify(params);
    let input4 = document.createElement("input");
    input4.type = "hidden";
    input4.name = "popedomTypes";
    input4.value = pTypes.join(",");
    let input5 = document.createElement("input");
    input5.type = "hidden";
    input5.name = "pOrgID";
    input5.value = pOrgID;
    let input6 = document.createElement("input");
    input6.type = "hidden";
    input6.name = "orgID";
    input6.value = orgID;
    div.appendChild(iframe)
    iframe.contentDocument.body.appendChild(form);//将表单放置在web中
    form.appendChild(input1);
    form.appendChild(input2);
    form.appendChild(input3);
    form.appendChild(input4);
    form.appendChild(input5);
    form.appendChild(input6);
    form.submit();
  }
  render() {
    const { controls, offsetHeight, paramValues, permID, url, userID, popedomTypes, odsDate, sjy, cmDate, menus } = this.props
    const record = paramValues[permID]
    const createButton = {
      name: 'createButton', required: false, type: 'button-group',
      data: [{ value: '1', label: '生成报表', onClick: this.createHandler.bind(this) }],
      grid: 4
    }
    let pTypes = popedomTypes[permID]
    let conts = controls[permID]
    if (!conts) {
      return null
    }
    if (pTypes.indexOf('4') === -1 && (permID === 4203 || permID === 4303)) {
      conts.splice(3, 1)
    }
    conts = [...conts, createButton]
    const info = this.state.isFirstLoad ? <span>请输入报表参数，并选择生成报表...</span> : null
    const iframeStyle = this.state.isFirstLoad ? { display: "none" } : { display: "block" }
    return (
      <div className={styles.normal} style={{ background: '#fff', marginTop: -16, padding: '5px 5px' }}>
        <div>
          <div className={styles.create} style={{ marginBottom: 0 }}>
            <EditFrom ref="reportForm" daoName={daoName} controls={conts} record={record} selectFirst={false} clearItemMargin={true} />
          </div>
          <div ref="ssrs_report">
          </div>
        </div>
      </div>
    )
  }
}
SSRS_Report.propTypes = {
  permID: PropTypes.number
};
function mapStateToProps(state) {
  const { controls, paramValues, url } = state.SSRS_Report;
  const { userID, orgID, pOrgID, popedomTypes, odsDate, sjy, cmDate, FTPDate } = state.menus;
  const { offsetHeight, offsetWidth, collapsedLeftMenu, menus } = state.menus
  return {
    userID,
    orgID,
    pOrgID,
    controls,
    paramValues,
    popedomTypes,
    url,
    offsetHeight,
    offsetWidth,
    collapsedLeftMenu,
    odsDate, sjy, cmDate, menus, FTPDate
  }
}
SSRS_Report = connect(mapStateToProps)(SSRS_Report)
export default SSRS_Report;

let render = (props) => React.createElement(SSRS_Report, props);
let f = new Factory()
f.set("SSRS_Report", render)
